<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\BaseController;
use app\common\model\User\User as UserModel;
use app\common\model\Post\Post as PostModel;
use app\common\model\Collect as CollectModel;
use app\common\validate\Collect as CollectValiDate;
use think\exception\ValidateException;

class Collect extends BaseController
{
    // 收藏列表
    public function index()
    {

    }

    // 收藏
    public function collect()
    {
        if($this->request->isAjax())
        {
            $LoginUser = !empty(cookie('LoginUser')) ? json_decode(cookie('LoginUser'),true) : [];

            $userid = !empty($LoginUser['id']) ? $LoginUser['id'] : 0;
            
            $postid = $this->request->param('postid');

            $User = UserModel::find($userid);

            $post = PostModel::find($postid);

            if(!$User)
            {
                $this->error('用户不存在');
            }

            if(!$post)
            {
                $this->error('帖子不存在');
            }

            $collect = CollectModel::where(['userid' => $userid,'postid' => $postid])->find();

            if($collect)
            {
                $result = $collect->delete();

                if($result === FALSE)
                {
                    $this->error('取消收藏帖子失败');
                }else{
                    $this->success('取消收藏帖子成功');
                }
            }else{
                // 没有收藏 收藏操作
                // 封装数据
                $data = [
                    'userid' => $userid,
                    'postid' => $postid
                ];

                try {
                    validate(CollectValiDate::class)->check($data);
                } catch (ValidateException $e) {
                    $this->error($e->getMessage());
                }

                $Collect = new CollectModel();

                $result = $Collect->save($data);

                if($result !== FALSE)
                {
                    $this->success('收藏帖子成功',null,['action' => 'collect']);
                }else{
                    $this->error('收藏帖子失败');
                }
            }
        }
    }
}